package com.ad.system;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;

public class HttpClientWrapper {

	private static Logger log = Logger.getLogger(HttpClientWrapper.class);

	public static void main(String[] args) {
		// Hashtable hs = new Hashtable();
		// hs.put("searchForDropDown", "Part Number");
		// hs.put("searchPhrase", "12124582");
		// hs.put("matchTypeDropDown", "Any Portion");
		// hs.put("perPageDropDown", "50");
		// hs.put("doPartNumberSearch", "true");
		// String pageSource = httpPost(
		// "http://www.powerandsignal.com/IDC/default.aspx", hs, "utf-8");
		// System.out.println(pageSource);
	}

	public static String httpGet(String url, String encoding) {
		// Create an instance of HttpClient.
		HttpClient client = new HttpClient();

		// Create a method instance.
		GetMethod method = new GetMethod(url);

		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
				new DefaultHttpMethodRetryHandler(3, false));

		String result = "";
		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
			}

			// Read the response body.
			byte[] responseBody = method.getResponseBody();
			// Deal with the response.
			// Use caution: ensure correct character encoding and is not binary
			// data
			if (!Common.isEmpty(encoding)) {
				result = new String(responseBody, encoding);
			} else {
				result = new String(responseBody);
			}

		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// Release the connection.
			method.releaseConnection();
		}

		return result;
	}

	@SuppressWarnings("unchecked")
	public static String httpPost(String url, Hashtable hstb, String uncode) {
		HttpClient httpClient = new HttpClient();
		int i = 0, len = hstb.size();
		InputStream ins = null;
		String pageSource = null;
		NameValuePair[] data = new NameValuePair[len];
		if (null != hstb) {
			for (Iterator iterator = hstb.keySet().iterator(); iterator
					.hasNext();) {
				String name = null;
				if (i < len) {
					name = (String) iterator.next();
					data[i] = new NameValuePair(name, hstb.get(name).toString());
				}
				i++;
			}
		}

		try {

			PostMethod postMethod = new PostMethod(url);
			doPost(httpClient, postMethod, data);

			// Header locationHeader = postMethod.getResponseHeader("location");
			// String locat = locationHeader.getValue();
			// if (null != locat) {
			// url = "http://www.haotq.com/" + locat;
			// postMethod = new PostMethod(url);
			// doPost1(httpClient, postMethod, data, locat);
			// }
			ins = postMethod.getResponseBodyAsStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(ins,
					uncode));
			StringBuffer sbf = new StringBuffer();
			String line = null;
			while ((line = br.readLine()) != null) {
				sbf.append(line);
			}
			/** 回收资源 */
			br.close();
			postMethod.releaseConnection();

			/** 页面源文�? */
			pageSource = sbf.toString();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return pageSource;
	}

	private static void doPost(HttpClient httpClient, PostMethod postMethod,
			NameValuePair[] data) throws IOException {
		// CharUtil.useProxy(httpClient);
		List<Header> headers = new ArrayList<Header>();
		headers.add(new Header("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
		headers.add(new Header("Content-Type",
				"application/x-www-form-urlencoded;charset=gb2312"));
		httpClient.getHostConfiguration().getParams().setParameter(
				"http.default-headers", headers);

		postMethod.setRequestBody(data);
		int statusCode = httpClient.executeMethod(postMethod);

		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
				|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			Header locationHeader = postMethod.getResponseHeader("location");
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
				System.out.println("The page was redirected to:" + location);
			} else {
				System.err.println("Location field value is null.");
			}
			return;
		} else {
			System.out.println("other");
		}

	}

	/**
	 * * Post获取
	 * 
	 * @param url
	 *            结果页面
	 * @param data
	 *            表单的�?
	 */
	@SuppressWarnings("unused")
	private static void doPost1(HttpClient httpClient, PostMethod postMethod,
			NameValuePair[] data, String locat) throws IOException {
		// CharUtil.useProxy(httpClient);
		List<Header> headers = new ArrayList<Header>();
		headers.add(new Header("User-Agent",
				"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"));
		headers.add(new Header("Content-Type",
				"application/x-www-form-urlencoded;charset=gb2312"));
		httpClient.getHostConfiguration().getParams().setParameter(
				"http.default-headers", headers);
		headers.add(new Header("Location", locat));
		postMethod.setRequestBody(data);
		int statusCode = httpClient.executeMethod(postMethod);

		if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
				|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
			Header locationHeader = postMethod.getResponseHeader("location");
			String location = null;
			if (locationHeader != null) {
				location = locationHeader.getValue();
				System.out.println("The page was redirected to:" + location);
			} else {
				System.err.println("Location field value is null.");
			}
			return;
		} else {
			System.out.println("other");
		}

	}
}
